/* eslint-disable no-shadow */
/* eslint-disable no-unused-vars */
import React, { memo, useState, useEffect, useRef, useCallback } from "react";
import Taro, {
  useRouter
} from "@tarojs/taro";
import { useSelector, useDispatch, shallowEqual } from "react-redux";
import { updateState } from "@/store/actions/global";
import { View } from "@tarojs/components";
import VirtualList from '@tarojs/components/virtual-list'
import { Transition, Loading, Empty, Tabs, Tab, Search } from "@antmjs/vantui";
import debounce from "lodash/debounce";
import axios from "@/axios";
import { getRecipeFilter } from "@/axios/api/recipe";
import Authorization from "@/components/Authorization";
import RecipeItem from "@/components/RecipeItem";
import BackTop from "@/components/BackTop";
import Navbar from "@/components/Navbar";
import toast from "@/utils/toast";
import { themeColor } from "../../utils/config";
import "./index.less";

const Index = () => {
  const router = useRouter();
  const dispatch = useDispatch();
  const { globalData } = useSelector(
    (state) => ({ globalData: state.globalData }),
    shallowEqual
  );
  const { isLogin, showBackTop, systemInfo, navbarHeight } = globalData;
  const { windowWidth, screenHeight } = systemInfo;
  const listRef = useRef();
  const [active, setActive] = useState(0);
  const [searchVal, setSearchVal] = useState(null);
  const [isLoading, setLoading] = useState(false);
  const [showTab, setShowTab] = useState(true);
  const [isMore, setIsMore] = useState(false);
  const [pageNum, setPageNum] = useState(1);
  const [list, setList] = useState([]);
  const [listHeight] = useState(
    screenHeight - navbarHeight - windowWidth * 200 / 750
  )
  const [itemSize] = useState(
    windowWidth * 230 / 750
  )
  const onChange = ({ detail: { index } }) => {
    const payload = {
      cat: searchVal,
      page: 1,
      type: index + 1
    };
    setList([]);
    setActive(index);
    getFilter(payload);
  };
  const getFilter = ({ cat, page = 1, type = 1 }) => {
    if (cat) {
      setLoading(true);
      let cats = (cat.trim().split(/\s+/));
      axios.post(getRecipeFilter, { cats, page, type }).then((res) => {
        const { data, code } = res;
        if (code === 200) {
          // const { list, pageNum, pageSize, total } = data;
          console.log(data, res.msg);
          const { pageNum, isMore, list } = data;
          if (page === 1) {
            setList(list);
            setIsMore(isMore)
            setPageNum(pageNum)
          } else {
            setList((pre) => [...pre, ...list]);
            setIsMore(isMore)
            setPageNum(pageNum)
          }
        }
        setLoading(false);
      });
    }
  };
  const handleClick = useCallback(
    debounce(
      (type, id, username) => {
        console.log("CLICK", type, id);
        let url = "";
        if (type === "recipe") {
          url = "/pages/recipeInfo/index?recipe_id=" + id;
        }
        if (type === "user") {
          url = `/pages/userCenter/index?user_id=${id}&username=${username}`;
        }
        if (!isLogin) {
          dispatch(
            updateState({
              isShowGrant: true,
            })
          );
        } else {
          jumpTo(url);
        }
      },
      500,
      {
        leading: true,
        trailing: false,
      }
    ),
    [isLogin]
  );
  const jumpTo = (url) => {
    Taro.navigateTo({
      url,
    });
  };
  const handleSearch = ({ detail }) => {
    setSearchVal(detail.trim());
  }
  useEffect(() => {
    if (!isLogin) {
      dispatch(
        updateState({
          isShowGrant: true,
        })
      );
      return;
    }
    const { cat } = router.params;
    setSearchVal(cat)
  }, [isLogin, dispatch]);
  useEffect(() => {
    setList([]);
    const payload = {
      cat: searchVal,
      page: 1,
      type: active + 1
    };
    getFilter(payload);
  }, [searchVal]);
  const pageScroll = ({ scrollDirection, scrollOffset }) => {
    const flag = scrollOffset > listHeight * 1.5;
    if (
      // 避免重复加载数据
      !isLoading &&
      // 只有往前滚动我们才触发
      scrollDirection === 'forward' &&
      // 200 = 滚动提前加载量，可根据样式情况调整
      scrollOffset > ((list.length - listHeight / itemSize) * itemSize - 200)
    ) {
      listReachBottom()
    }
    if (flag !== showBackTop) {
      dispatch(updateState({
        showBackTop: flag
      }))
    }
  }
  const listReachBottom = (() => {
    if (isMore) {
      const payload = {
        cat: searchVal,
        page: pageNum + 1,
        type: active + 1
      };
      getFilter(payload);
    }
  });
  const BackToTop = () => {
    listRef.current.scrollTo(0);
  }
  const Row = React.memo(({ data, index }) => {
    return (
      <RecipeItem
        data={data[index]}
        handleClick={handleClick}
      ></RecipeItem>
    );
  })
  return (
    <View className='search'>
      <Authorization canClose={false}></Authorization>
      <Navbar title='菜谱搜索' arrow='true'></Navbar>
      <View>{showBackTop ? <BackTop onClick={BackToTop} top={.75 * screenHeight} /> : null}</View>
      <View style={{ top: navbarHeight }} className='m-top'>
        <View className='m-input'>
          <Search
            value={searchVal}
            onSearch={(e) => handleSearch(e)}
            onCancel={() => { }}
            shape='round'
            maxlength='15'
            background='#ffffff'
            placeholder='今天想吃什么'
          />
        </View>
        <Transition className='m-tabs' show={showTab}>
          <Tabs active={active} onChange={onChange} >
            <Tab title='最新发布'>
            </Tab>
            <Tab title='点赞最多'>
            </Tab>
            <Tab title='评分最高'>
            </Tab>
            <Tab title='热度最高'>
            </Tab>
          </Tabs>
        </Transition>
      </View>
      <View className='block'></View>
      <View className='m-result' style={{ height: listHeight }}>
        {!list.length && !isLoading ? <Empty description='暂无菜谱' /> :
          <VirtualList
            className='virList'
            height={listHeight} /* 列表的高度 */
            width='100%' /* 列表的宽度 */
            itemData={list} /* 渲染列表的数据 */
            itemCount={list.length} /*  渲染列表的长度 */
            itemSize={itemSize} /* 列表单项的高度  */
            overscanCount={5}  /*在可视区域之外渲染的列表单项数量，值设置得越高，快速滚动时出现白屏的概率就越小，相应地，每次滚动的性能会变得越差。*/
            ref={listRef}
            renderBottom={
              isLoading ? (
                <View className='loading'>
                  <Loading color={themeColor} size='28px' />
                </View>
              ) : null
            }
            onScroll={pageScroll}
          >
            {Row}
          </VirtualList>
        }
      </View>

    </View>
  );
};

export default memo(Index);
